<template>
  <div id="categoryTagManagePage">
    <a-flex justify="space-between">
      <h2>分类标签管理</h2>
      <a-space>
        <a-button
          type="primary"
          @click="showAddModal()">+ 创建分类/标签
        </a-button>
      </a-space>
    </a-flex>

    <div style="margin-bottom: 16px" />

    <!-- 搜索表单 -->
    <a-form layout="inline" :model="searchParams" @finish="doSearch">
      <a-form-item label="类别" name="type">
        <a-select
          v-model:value="searchParams.type"
          :options="CATEGORYTAG_TYPE_OPTIONS"
          placeholder="请输入类别"
          style="min-width: 180px"
          allow-clear
        />
      </a-form-item>

      <a-form-item label="创建用户 id">
        <a-input v-model:value="searchParams.userId" placeholder="请输入用户 id" allow-clear />
      </a-form-item>

      <a-form-item>
        <a-button type="primary" html-type="submit">搜索</a-button>
      </a-form-item>

    </a-form>
    <div style="margin-bottom: 16px" />
    <!-- 表格 -->
    <a-table
      :columns="columns"
      :data-source="dataList"
      :pagination="pagination"
      @change="doTableChange"
    >
      <template #bodyCell="{ column, record }">
        <!-- 空间类别 -->
        <template v-if="column.dataIndex === 'type'">
          <a-tag :style="{ color: record.type === 0 ? 'red' : 'green' }">
            {{ CATEGORYTAG_TYPE_MAP[record.type] }}
          </a-tag>
        </template>
        <!--        创建时间-->
        <template v-if="column.dataIndex === 'createTime'">
          {{ dayjs(record.createTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>
        <!--        编辑时间-->
        <template v-if="column.dataIndex === 'editTime'">
          {{ dayjs(record.editTime).format('YYYY-MM-DD HH:mm:ss') }}
        </template>

        <template v-else-if="column.key === 'action'">
          <a-space wrap>
            <!--            空白页-->
            <!--修改操作列-->
            <a-button
              type="primary"
              @click="showEditModal(record.id)">编辑</a-button>

            <span width="20px">&nbsp;&nbsp;&nbsp;</span>

            <a-popconfirm
              danger
              v-if="dataList.length"
              title="确认删除该分类标签?"
              ok-text="确认"
              cancel-text="取消"
              @confirm="doDelete(record.id)"
            >
              <a-button danger >删除</a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </template>
    </a-table>

    <!-- 编辑分类标签信息的模态框 -->
    <a-modal
      v-model:visible="editModalVisible"
      title="编辑分类标签名称"
      @ok="handleEditModalOk"
      @cancel="handleEditModalCancel"
    >
      <a-form :model="editCategoryTag">

        <a-form-item label="名称">
          <a-input v-model:value="editCategoryTag.name" />
        </a-form-item>
      </a-form>
    </a-modal>

    <!-- 新增分类标签信息的模态框 -->
    <a-modal
      v-model:visible="addModalVisible"
      title="新增分类标签"
      @ok="handleAddModalOk"
      @cancel="handleAddModalCancel"
    >
      <a-form :model="addCategoryTag">

        <a-form-item label="类型">
          <a-select
            v-model:value="addCategoryTag.type"
            style="min-width: 180px"
            placeholder="请选择类型"
            :options="CATEGORYTAG_TYPE_OPTIONS"
            allow-clear
          />
        </a-form-item>

        <a-form-item label="名称">
          <a-input v-model:value="addCategoryTag.name" />
        </a-form-item>

      </a-form>

    </a-modal>


  </div>
</template>
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import { message } from 'ant-design-vue'
import dayjs from 'dayjs'
import {
  addCategoryTagUsingPost,
  deleteCategoryTagUsingPost,
  listCategoryTagByPageUsingPost,
  updateCategoryTagUsingPost
} from '@/api/categoryTagController.ts'
import { CATEGORYTAG_TYPE_MAP, CATEGORYTAG_TYPE_OPTIONS } from '../../constants/categoryTag.ts'

const columns = [
  {
    title: 'id',
    dataIndex: 'id',
    width: 80,
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '类别',
    dataIndex: 'type',
  },
  {
    title: '创建用户id',
    dataIndex: 'userId',
    width: 80,
  },
  {
    title: '创建时间',
    dataIndex: 'createTime',
  },
  {
    title: '编辑时间',
    dataIndex: 'editTime',
  },
  {
    title: '操作',
    key: 'action',
  },
]

// 定义数据
const dataList = ref<API.CategoryTag[]>([])
const total = ref(0)

const loading = ref(false)

// 搜索条件
const searchParams = reactive<API.CategoryTagQueryRequest>({
  current: 1,
  pageSize: 10,
  sortField: 'editTime',
  sortOrder: 'descend',
})

// 获取数据
const fetchData = async () => {
  loading.value = true
  const res = await listCategoryTagByPageUsingPost({
    ...searchParams,
  })
  if (res.data.code === 0 && res.data.data) {
    dataList.value = res.data.data.records ?? []
    total.value = res.data.data.total ?? 0
  } else {
    message.error('获取数据失败，' + res.data.message)
  }
  loading.value = false
}

// 页面加载时获取数据，请求一次
onMounted(() => {
  fetchData()
})

// 分页参数
const pagination = computed(() => {
  return {
    current: searchParams.current,
    pageSize: searchParams.pageSize,
    total: total.value,
    showSizeChanger: true,
    showTotal: (total) => `共 ${total} 条`,
  }
})

// 表格变化之后，重新获取数据
const doTableChange = (page: any) => {
  loading.value = true
  searchParams.current = page.current
  searchParams.pageSize = page.pageSize
  fetchData()
  loading.value = false
}

// 搜索数据
const doSearch = () => {
  // 重置页码
  searchParams.current = 1
  fetchData()
}



// 删除数据
const doDelete = async (id: string) => {
  loading.value = true
  if (!id) {
    return
  }
  const res = await deleteCategoryTagUsingPost({ id })
  if (res.data.code === 0) {
    message.success('删除成功')
    // 刷新数据
    fetchData()
  } else {
    message.error('删除失败'+res.data.message)
  }
  loading.value = false
}

//编辑数据

// 控制编辑模态框的显示
const editModalVisible = ref(false)

//定义一个名叫 editCategoryTag 的响应式对象，用来存储要编辑分类标签对象的信息
let editCategoryTag:API.CategoryTag = reactive({
  id: 0,
  name: '',
})

// 显示编辑模态框，并填充数据
const showEditModal = (id: number) => {
  for (const key in dataList.value) {
    if (dataList.value[key].id === id) {
      editCategoryTag = dataList.value[key]
    }
  }
  editModalVisible.value = true
}

// 处理编辑模态框的确认事件
const handleEditModalOk = () => {
  doChange(editCategoryTag)
  editModalVisible.value = false
}
// 处理编辑模态框的取消事件
const handleEditModalCancel = () => {
  editModalVisible.value = false
}

//修改数据
const doChange = async (editCategoryTag:API.CategoryTag) => {
  const res = await updateCategoryTagUsingPost(editCategoryTag)
  if (res.data.code === 0) {
    message.success('修改成功')
  } else {
    message.error('修改失败'+res.data.message)
  }
  // 刷新数据
  fetchData()
}

// 控制新增模态框的显示
const addModalVisible = ref(false)

//定义一个名叫 addCategoryTag 的响应式对象，用来存储要新增分类标签对象的信息
const addCategoryTag = reactive<API.CategoryTagAddRequest>({})

// 显示新增模态框，并填充数据
const showAddModal = () => {
  addModalVisible.value = true
}

// 处理编辑模态框的确认事件
const handleAddModalOk = () => {
  doChangeWithAdd(addCategoryTag)
  addModalVisible.value = false
}
// 处理编辑模态框的取消事件
const handleAddModalCancel = () => {
  addModalVisible.value = false
}

//新增数据
const doChangeWithAdd = async (addCategoryTag:API.CategoryTagAddRequest) => {
  const res = await addCategoryTagUsingPost(addCategoryTag)
  if (res.data.code === 0) {
    message.success('添加成功')
    addCategoryTag.name = ''
    addCategoryTag.type = undefined
    // 刷新数据
    fetchData()
  } else {
    message.error('添加失败'+res.data.message)
  }
  addModalVisible.value = false
}

</script>
